package 迭代遍历;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;

/**
 * @author: zhengtao
 * @description: 二叉树的后序遍历 ,因为前序遍历是
 *               前序：中左右---------->前序左右子节点入栈顺序改变  中右左， 翻转数组或者list后就得到了后序遍历
 *               后续：左右中，
 * @version: 1.0
 * @date: 2022/10/29  09:51
 */
public class Demo145 {
    List<Integer> res=new ArrayList<>();

    public List<Integer> postorderTraversal(TreeNode root) {
        Stack<TreeNode>  stack=new Stack<>();
        stack.push(root);
        while (!stack.empty()){
            TreeNode pop = stack.pop();
            if(pop!=null){
                res.add(pop.val);
                stack.push(pop.left);
                stack.push(pop.right);
            }
        }
         Collections.reverse(res);
        return res;
    }
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
